//
//  ViewController.m
//  TestCode
//
//  Created by Tracy on 16/9/3.
//  Copyright © 2016年 yule. All rights reserved.
//

#import "ViewController.h"
#import <TFHpple.h>
#import <HexColors.h>
typedef NS_ENUM(NSUInteger,kParserContentType) {
    kParserContentTypeReturn,
    kParserContentTypeFont,
    kParserContentTypeText,
    kParserContentTypeImg,
    kParserContentTypeLink
};
@interface ViewController ()<NSLayoutManagerDelegate,UITextViewDelegate>
@property (nonatomic,strong) UIScrollView *scroll;
@property (nonatomic,strong) UITableView  *tableView;
@property (nonatomic,strong) NSMutableArray *data;
@property (nonatomic,strong) UILabel      *textLabel;
@property (nonatomic,strong) UITextView   *textView;

@end

@implementation ViewController{
    CGSize _contentSize;
    NSMutableArray *_data;
}

- (UITextView *)textView{
    if (!_textView) {
        _textView = [[UITextView alloc] initWithFrame:CGRectInset(self.view.bounds, 5, 20)];
//        NSLayoutManager *layoutManager = _textView.layoutManager;
//        layoutManager.delegate = self;
     
        _textView.scrollEnabled = NO;
    }
    return _textView;
}
- (UILabel *)textLabel{
    if (!_textLabel) {
        _textLabel = ({
            UILabel *subLabel = [UILabel new];
            subLabel.numberOfLines = 0;
            subLabel;
        });
    }
    return _textLabel;
}

- (UIScrollView *)scroll{
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scroll.backgroundColor = [UIColor whiteColor];
    }
    return _scroll;
}

-(BOOL)layoutManager:(NSLayoutManager *)layoutManager shouldBreakLineByWordBeforeCharacterAtIndex:(NSUInteger)charIndex
{
    NSRange range;
    NSURL *linkURL = [layoutManager.textStorage attribute:NSLinkAttributeName atIndex:charIndex effectiveRange:&range];
    
    // Do not break lines in links unless absolutely required
    if (linkURL && charIndex > range.location && charIndex <= NSMaxRange(range))
        return NO;
    else
        return YES;
}

- (CGFloat)layoutManager:(NSLayoutManager *)layoutManager lineSpacingAfterGlyphAtIndex:(NSUInteger)glyphIndex withProposedLineFragmentRect:(CGRect)rect
{
    return floorf(glyphIndex / 100);
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    self.view.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"#000080"];
    _data = [NSMutableArray array];
     NSString *code = @"<b><font color=#000080><font color='Red'>报名成功的网友有（包含微信、微博、快拍）：李争、草鱼妹、卢观婷、胡琳、方艺、华琦、沈遥耀、叶丹、林锦妮、贺大江、李娜、甘晓玲、王飞超、陶佳莉、黄怡如、张雅妮、汪斯遥、吴珂岩、周志婷、乔丹丹、李敏、黄蔚、陆蔚婷、李新燕、杨千越、冯玉婷、童心笛。</font></font></b><br /><br />从《鲛人歌》到《鹿童谣》，从《消夏令》到《素羽》，扣桑的每一组作品，都如同一首诗。<br />但，与其说是一首诗，不如说，是扣桑用摄影的方式，让一首诗有了正确的打开方式，抑或，阅读的方式。<br /><br />她的照片温润如画，如夏日里的一股清泉让人平静下来却又思绪万千。<br />她的镜头下人物百态却都优雅自然。<br />每张照片独立成诗，却又能连成故事。安静却又充满张力，简约却又意味深长。<br />她像一个胸有成竹的隐士，不急不慢，娓娓道来。<br /><br />9月20日，她影像线下私享会巡游<b><font color=#000080>杭州</font></b>，特与影像小伙伴<img src=http://forum.xitek.com/pics/201509/20500/2050066/2050066_1442037907.jpg  border=0>一同邀约摄影师扣桑做客本期私享会。我们可以一起走进扣桑的世界，一起感受她作品中温柔的力量，以及安静的震撼力。<br /><br /><b><font color=#000080>摄影师介绍</font></b>：<br /><img src=http://forum.xitek.com/pics/201509/20500/2050066/2050066_1442038125.jpg ><br /><br />扣桑，原名林弘，89年自由少女摄影师，<br />出生福建，江南大学设计学院广告学专业，<br />2015年3月成立工作室“一块扣肉”并由北京转战杭州。<br /><br /><b><font color=#000080>使用器材</font></b>：EOS 5D Mark II<br /><br /><b><font color=#000080>活动时间：</font></b>9月20日（星期日）<font color=Red>上午10:00-12:00</font><br /><br /><b><font color=#000080>招募人数：</font></b>无忌<font color=Red>女泡菜</font> <b><font color=#000080>25</font></b> 名<br /><br /><b><font color=#000080>活动地点：</font></b>拉姆咖啡青年店<br /><br /><b><font color=#000080>详细地址：</font></b><b><font color=#000080><font color=Red>杭州</font>青年路27号2楼（近基督教青年会酒店）</font></b><br /><br /><b><font color=#000080>活动流程<br />时间    内容</font></b><br /><font color=Red>09：30-10：00</font> 网友签到。<br /><font color=Red>10：00-11：00</font> 讲座开始，由扣桑分享拍摄人像的心得和经历。<br /><font color=Red>11：00-11：50</font> 网友提问互动，与扣桑讨论摄影技巧和摄影心得。<br /><font color=Red>11：50-12：00</font> 赠送礼品，集体合影，问卷调查，活动结束。<br /><br /><b><font color=#000080>摄影师作品赏析</font></b><br /><img src=http://forum.xitek.com/pics/201509/20500/2050066/2050066_1442038910.jpg  border=0><br /><br /><a href=http://ww.xitek.com/photoladies/yueshijie/201508/24-184667.html target=_blank>点击这里，欣赏扣桑更多作品</a>";
    code = [code stringByReplacingOccurrencesOfString:@"<br />" withString:@"\n"];
    code = [code stringByReplacingOccurrencesOfString:@"<b>" withString:@""];
    code = [code stringByReplacingOccurrencesOfString:@"</b>" withString:@""];
    code = [code stringByReplacingOccurrencesOfString:@"<p>" withString:@""];
    code = [code stringByReplacingOccurrencesOfString:@"</p>" withString:@""];
    NSArray *codes = [code componentsSeparatedByString:@"\n"];
    for (NSString *shortStr in codes) {
        if (shortStr.length>0) {
            NSData  * data      = [shortStr dataUsingEncoding:NSUTF8StringEncoding];
            TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:data];
            NSArray * elements  = [doc searchWithXPathQuery:@"/html/body/*"];
            for (TFHppleElement *child in elements) {
                    if ([child.tagName isEqualToString:@"font"]) {
                        for (TFHppleElement *a in [child children]) {
                            if ([a.tagName isEqualToString:@"font"]) {
                                [self parserContentWithTFHppleElement:a withType:kParserContentTypeFont];
                            }else if ([a.tagName isEqualToString:@"text"]){
                                [self parserContentWithTFHppleElement:a withType:kParserContentTypeText];
                            }
                        }
                    }else if ([child.tagName isEqualToString:@"a"]){
                        [self parserContentWithTFHppleElement:child withType:kParserContentTypeLink];
                    }else if([child.tagName isEqualToString:@"p"]){
                        for (TFHppleElement *b in [child children]) {
                            if ([b.tagName isEqualToString:@"font"]) {
                                [self parserContentWithTFHppleElement:b withType:kParserContentTypeFont];
                            }else if ([b.tagName isEqualToString:@"text"]){
                                [self parserContentWithTFHppleElement:b withType:kParserContentTypeText];
                            }else if ([b.tagName isEqualToString:@"img"]){
                               [self parserContentWithTFHppleElement:b withType:kParserContentTypeImg];
                            }
                        }
                    }else if ([child.tagName isEqualToString:@"img"]) {
                        [self parserContentWithTFHppleElement:child withType:kParserContentTypeImg];
                    }
                }
        }else{
            [self parserContentWithTFHppleElement:nil withType:kParserContentTypeReturn];
        }
    }
}

- (void)parserContentWithTFHppleElement:(TFHppleElement*)element withType:(kParserContentType)type{
    switch (type) {
        case kParserContentTypeFont: {
            [_data addObject:@{
                               @"contentType":[element tagName],                                                    @"content":[element text],
                                @"attributes":[element attributes]
                               }];
            break;
        }
        case kParserContentTypeText: {
            [_data addObject:@{
                                    @"contentType":[element tagName],                                                    @"content":[element content],
                                     @"attributes":[element attributes]
                                    }];
            break;
        }
        case kParserContentTypeImg: {
            [_data addObject:@{
                                    @"contentType":[element tagName],
                                        @"content":[element objectForKey:@"src"],
                                     @"attributes":[element attributes]
                                    }];
            break;
        }
        case kParserContentTypeLink: {
            [_data addObject:@{
                                    @"contentType":[element tagName],                                                    @"content":[element objectForKey:@"href"],
                                     @"attributes":[element attributes]
                                    }];
            break;
        }
        case kParserContentTypeReturn:{
            [_data addObject:@{
                               @"contentType":@"br",
                                   @"content":@"\n",
                               @"attributes":@{}
                               }];
            break;
        }
    }
}
//
- (NSRegularExpression *)regularBr{
    static NSRegularExpression *regex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 微博的 At 只允许 英文数字下划线连字符，和 unicode 4E00~9FA5 范围内的中文字符，这里保持和微博一致。。
        // 目前中文字符范围比这个大
        regex = [NSRegularExpression regularExpressionWithPattern:@"" options:kNilOptions error:NULL];
    });
    return regex;
}
- (CGSize)heightWithAttributeText:(NSAttributedString *)text constrainedToWidth:(CGFloat)width{
    CGFloat titleHeight;
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width,CGFLOAT_MAX)
                                     options:options
                                     context:nil];
    titleHeight = ceilf(rect.size.height)+20;
    return CGSizeMake(width, titleHeight);
}

- (NSAttributedString *)scaleImageWithAttributeText:(NSAttributedString *)text withWidth:(CGFloat)width{
    [text enumerateAttribute:NSAttachmentAttributeName
                     inRange:NSMakeRange(0, text.length)
                     options:0
                  usingBlock:^(id value, NSRange range, BOOL *stop)
     {
         if ([value isKindOfClass:[NSTextAttachment class]])
         {
             NSTextAttachment *attachment = (NSTextAttachment *)value;
             UIImage *image = [attachment imageForBounds:[attachment bounds]
                                           textContainer:nil
                                          characterIndex:range.location];
             if ([attachment.fileType isEqualToString:@"public.jpeg"]) {
                 CGFloat scale = image.size.width/image.size.height;
                 if (image.size.width<=width) {
                     attachment.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
                     return;
                 }
                 CGFloat height = width/scale;
                 attachment.bounds = CGRectMake(([UIScreen mainScreen].bounds.size.width-width)/2, 0, width, height);
             }
         }
     }];
    return text;
}
- (NSAttributedString *)scaleImageWithText:(NSString *)text withWidth:(CGFloat)width{
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:text];
    [str enumerateAttribute:NSAttachmentAttributeName
                     inRange:NSMakeRange(0, text.length)
                     options:0
                  usingBlock:^(id value, NSRange range, BOOL *stop)
     {
         if ([value isKindOfClass:[NSTextAttachment class]])
         {
             NSTextAttachment *attachment = (NSTextAttachment *)value;
             UIImage *image = [attachment imageForBounds:[attachment bounds]
                                           textContainer:nil
                                          characterIndex:range.location];
             if ([attachment.fileType isEqualToString:@"public.jpeg"]) {
                 CGFloat scale = image.size.width/image.size.height;
                 if (image.size.width<=width) {
                     attachment.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
                     return;
                 }
                 CGFloat height = width/scale;
                 attachment.bounds = CGRectMake(([UIScreen mainScreen].bounds.size.width-width)/2, 0, width, height);
             }
         }
     }];
    return str;
}
//将HTML字符串转化为NSAttributedString富文本字符串
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                               NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange{
    NSLog(@"haha");
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange{
    return YES;
}
@end
